<template>
  <!-- 营业执照信息 / 详情 / 完善营业执照信息 -->
  <view class="charterLicense">
    <view class="wrapper">
      <view class="wrapper-item content" :class="orFlag == 3 ? 'detailOrflag' : ''">
        <block v-if="orFlag == 1 || orFlag == 2">
          <u-form :model="form" ref="form" label-width="100" :error-type="errorType">
            <u-form-item label="证件图片" label-width="70">
              <text style="color: #a1a1a1; font-size: 26rpx">
                (大小2M以内)
              </text>
            </u-form-item>
            <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="file" :maxCount="1"
              width="100" height="80">
              <image :src="baseImgUrl + 'upload-icon3.png'" style="width: 200rpx; height: 160rpx"></image>
            </u-upload>

            <u-form-item label="企业名称" borderBottom label-width="70">
              <u--input v-model.trim="form.businessName" border="none" placeholder="请填写" :maxlength="18"></u--input>
            </u-form-item>

            <u-form-item label="信用代码" borderBottom label-width="70">
              <u--input v-model.trim="form.creditCode" border="none" placeholder="请填写" :maxlength="22"></u--input>
            </u-form-item>
            <!-- ===============================a -->
          </u-form>
        </block>
        <block v-if="orFlag == 3">
          <u-form-item label="证件图片" label-width="70"> </u-form-item>
          <image :src="imgPrefix + form.businessLicenseUrl" mode="aspectFill" style="width: 200rpx; height: 160rpx"
            @click="pvwImage([imgPrefix + form.businessLicenseUrl])"></image>

          <u-form-item label="企业名称" borderBottom label-width="70">
            <u--input v-model.trim="form.businessName" border="none" readonly></u--input>
          </u-form-item>

          <u-form-item label="信用代码" borderBottom label-width="70">
            <u--input v-model.trim="form.creditCode" border="none" readonly></u--input>
          </u-form-item>
        </block>
      </view>
    </view>

    <view class="btns thispageBtn" v-if="options.companyStatus != 3 && orFlag != 3">
      <block v-if="orFlag == 1 || orFlag == 2">
        <button class="cancel-btn lt" type="primary" @click="navBack('back', 1, 1)">
          取消
        </button>
        <button class="submit-btn" type="primary" @click="submitHandle">
          保存
        </button>
      </block>
      <!-- <button
        v-if="orFlag == 3"
        class="submit-btn"
        type="primary"
        @click="editHandle"
        icon="map"
        style="width: 100%"
      >
        修改
      </button> -->
    </view>
  </view>
</template>

<script>
  import {
    businessDetail,
    saveBusiness
  } from "@/api/myself.js";
  import {
    Toast,
    navBack,
    handleClickRouter,
    uniTrim,
    pvwImage,
    getBase64Two,
    checkSocialCardNumber,
    medicalTreatment,
    registerNumber,
    getHeader,
    uploadFile,
  } from "@/utils/util.js";

  export default {
    name: "charterLicense",
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        baseURL: this.$baseURL,
        clientId: this.$clientId,
        clientSecret: this.$clientSecret,
        options: {},
        form: {},
        errorType: ["none"],
        orFlag: 1, // 1：添加   2：编辑  3：详情
        fileList: [],
        imgPrefix: uni.getStorageSync("imgPrefix"),
      };
    },
    onLoad(options) {
      this.options = options;

      if (options.businessStatus == 0 && options.companyStatus != 3) {
        uni.setNavigationBarTitle({
          title: "完善营业执照信息",
        });
        businessDetail({
          companyId: options.id
        }).then((res) => {
          if (res.code == 200) {
            this.form = res.result;
            const {
              businessLicenseUrl
            } = res.result
            if (businessLicenseUrl) {
              this.fileList.push({
                url: this.imgPrefix + businessLicenseUrl,
              });
            }
          }
        });
      }

      if (options.businessStatus != 0) {
        this.orFlag = 3;
        businessDetail({
          companyId: options.id
        }).then((res) => {
          if (res.code == 200) {
            this.form = res.result;
            const {
              businessLicenseUrl
            } = res.result
            if (businessLicenseUrl) {
              this.fileList.push({
                url: this.imgPrefix + businessLicenseUrl,
              });
            }
          }
        });
        // certificateDetail({ companyId: options.id }).then((res) => {
        //   let { certificateCodeList, certificateUrl, certificateTime } =
        //     res.result;
        //   this.form = res.result;
        //   this.form.ccieFirst = certificateCodeList[0] || "";
        //   this.form.ccieSecond = certificateCodeList[1];
        //   this.form.ccieThird = certificateCodeList[2];
        //   this.form.certificateDateName = formatters(certificateTime, "YY/MM/DD");
        //   this.form.certificateDate = dayTurnTime(this.form.certificateDateName);
        //   this.fileList.push({
        //     url: this.imgPrefix + certificateUrl,
        //   });
        // });
      }
    },
    methods: {
      handleClickRouter,
      navBack,
      pvwImage,
      editHandle() {
        this.orFlag = 2;
      },
      afterRead(info) {
        let _this = this;

        uni.request({
          url: "https://aip.baidubce.com/oauth/2.0/token",
          method: "GET",
          data: {
            grant_type: "client_credentials",
            client_id: _this.clientId,
            client_secret: _this.clientSecret,
          },
          success(res) {
            _this.base64Business(res.data.access_token, info);
          },
        });
      },
      base64Business(token, info) {
        let _this = this;
        _this.uploadImage(info.file.url, 2);
        getBase64Two(info.file.url)
          .then((res) => {
            return res;
          })
          .then((res) => {
            uni.request({
              url: `https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?access_token=${token}`,
              method: "POST",
              header: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
              data: {
                id_card_side: "front",
                image: res,
              },
              success(resbai) {
                let {
                  statusCode,
                  data
                } = resbai;
                if (statusCode == 200 && data && data.words_result && data.words_result["单位名称"]) {
                  _this.$set(
                    _this.form,
                    "businessName",
                    data.words_result.单位名称.words
                  );
                  _this.$set(
                    _this.form,
                    "creditCode",
                    data.words_result.社会信用代码.words
                  );
                  return;
                }
              },
            });
          });
      },
      uploadImage(fileurl, type) {
        let _this = this;

        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: fileurl,
            name: "file",
            formData: {
              type: type,
            },
          })
          .then((res) => {
            let {
              fullPath,
              halfPath
            } = res.result;

            if (type == 2) {
              // 营业执照的
              _this.fileList.push({
                url: fullPath
              });
              _this.form.businessLicenseUrl = halfPath;
            }
          })
          .finally(() => {

          })
      },
      deletePic() {
        this.fileList = [];
        this.form.businessLicenseUrl = "";
      },
      submitHandle() {
        let {
          businessLicenseUrl,
          businessName,
          creditCode
        } = this.form;

        // if (!businessName || !uniTrim(businessName)) {
        //   Toast("请输入企业名称");
        //   return;
        // }

        // if (!creditCode || !uniTrim(creditCode)) {
        //   Toast("请输入信用代码");
        //   return;
        // }

        // let check = checkSocialCardNumber(creditCode);
        // let medical = medicalTreatment(creditCode);
        // let refisNum = registerNumber(creditCode);
        // if (!check && !medical && !refisNum) {
        //   Toast("请输入正确的信用代码");
        //   return;
        // }

        let data = {
          id: this.options.id,
          businessLicenseUrl: businessLicenseUrl,
          businessName: businessName,
          creditCode: creditCode,
        };

        saveBusiness(data).then((res) => {
          if (res.code == 200) {
            Toast("保存成功");
            navBack("back", 2);
            return;
          }
          Toast(res.message);
        });
      },
    },
  };
</script>

<style>
  page {
    background-color: #f3f3f3 !important;
    height: 100%;
  }
</style>
<style lang="scss" scoped>
  .charterLicense {
    flex: 1;
    background-color: #f3f3f3;

    .charterLicense-title {
      position: absolute;
      top: 10rpx;
      left: 6%;
      color: #ffffff;
      font-size: 34rpx;
      font-weight: bold;
    }

    .wrapper {
      position: absolute;
      top: 30rpx;
      left: 50%;
      transform: translateX(-50%);

      .wrapper-item {
        margin-bottom: 2vh;
        padding: 35rpx 40rpx;
        background-color: #ffffff;
        border-radius: 10rpx;
        width: 702rpx;
      }

      .content {
        margin: 0 auto;
        height: calc(100vh - 90px);
        overflow-y: auto;
      }

      .detailOrflag {
        height: calc(100vh - 30px);
      }
    }

    .special-class {
      display: flex;

      view {
        width: 160rpx;
        display: flex;

        /deep/.u-input {
          width: 60% !important;
        }
      }

      view:nth-of-type(3) {
        width: 300rpx;
      }

      /deep/input {
        padding-right: 0;
      }

      span {
        padding-top: 18rpx;
        font-size: 30rpx;
      }
    }

    .thispageBtn {
      position: absolute;
      width: 100vw;
      bottom: 0;
    }
  }
</style>